JavaScript

A5.u.arraysearch Method

Syntax

A5.u.array.search(array,search[,start])

Arguments

arrayarray

The array to search.

searchobjectstringfunction

The value(s) to search for. If an object is passed in then each property in the search object will be the searched for value of that property in the array items. A string can be passed into search for a partial match in an array of strings. If a function is passed in then it will be called with each array item.

startnumber

The index on the array to start searching from. A negative value will be offset from the end of the array with "-1" being the last index.

Returns

indexnumber

The index of the first match (after the optionally specified start index).

Description

Search an array for a value(s).

Discussion

The A5.u.array.search method allows for searching arrays for "partial" matches. This is most useful in the context of an array of objects.

If an object is passed in then each property of the "search" object will look at the corresponding property in each array item. For example a search object with a property of "firstname" set to "Bob", will search each array items "firstname" property and check if it is equal to "Bob". String searched can be partial searches. To define a partial search an the value of the property in the "search" object is defined as an array. The first item of this array is the operation, while the second is the value. Supported operations are "==" (the default), "===", "starts-with" and "contains". All search operations except "===" are case-insensitive.

Custom searches can be don by passing in a function that will receive the array item data as well as the index. This function should return false if the item is not a match and true if it is.

Example

var arr = [
	{"Firstname":"John","Lastname":"Smith","City":"Boston","State":"MA"},
	{"Firstname":"Henry","Lastname":"Rhodes","City":"New York","State":"NY"},
	{"Firstname":"Allison","Lastname":"Richards","City":"New York","State":"NY"},
	{"Firstname":"Amanda","Lastname":"Sanders","City":"Burlington","State":"MA"},
	{"Firstname":"Nancy","Lastname":"Clark","City":"Boston","State":"MA"},
	{"Firstname":"Cecelia","Lastname":"Dawkins","City":"Buffalo","State":"NY"},
	{"Firstname":"Kathy","Lastname":"Morton","City":"New York","State":"NY"}
]
var indx = A5.u.array.search(arr,{"City": "boston", "Lastname": ["starts-with","c"]});
// indx = 4
indx = A5.u.array.search(arr,{"City": "new york"},3);
// indx = 6